import axios from 'axios'
import router from '@/router/routers'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import Config from '@/config'

const req = {
  service: axios.create({
    baseURL: process.env.BASE_API, // api 的 base_url
    timeout: Config.timeout // 请求超时时间
  }),
  // 是否启用默认错误提示，默认不提示
  isHint: true,
  // 是否是文件上传
  isFile: false
}

// request拦截器
req.service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    if (req.isFile) {
      config.headers['Content-Type'] = 'multipart/form-data'
    } else {
      config.headers['Content-Type'] = 'application/json'
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
req.service.interceptors.response.use(
  response => {
    const data = response.data
    // 只有code码为0，才是正常，其他均为失败.
    if (data.code !== 0) {
      // 是否提示错误信息
      if (req.isHint) {
        Message.error(data.msg)
      }
      return Promise.reject(data)
    }
    return data
  },
  error => {
    const response = error.response
    const data = response.data
    const status = response.status
    if (status === 401) {
      MessageBox.confirm(
        '登陆失败，或者登录状态已过期',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('Logout').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else if (status === 403) {
      router.push({ path: '/401' })
    } else {
      Notification.error({
        title: data.message,
        duration: 2000
      })
    }
    return Promise.reject(data)
  }
)

export default function(options, isHint, isFile) {
  if (isHint === undefined) {
    isHint = false
  }
  if (isFile === undefined) {
    isFile = false
  }
  req.isHint = isHint
  req.isFile = isFile
  return req.service(options)
}
